﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StackExchange.Redis;
using System.DirectoryServices.ActiveDirectory;
using System.Dynamic;

namespace Msung.Core.Caching
{
    public class RedisOperationRepository : IRedisOperationRepository
    {

        private readonly IDatabase _database;
        private readonly ConnectionMultiplexer _redis;
        private readonly ILogger<RedisOperationRepository> _logger;
        IDatabase database;

        public RedisOperationRepository(
            ConnectionMultiplexer redis,
            ILogger<RedisOperationRepository> logger
            )
        {
            _redis = redis;
            _logger = logger;
            _database = redis.GetDatabase();
        }
        private IServer GetServer(int i = 0)
        {
            var endpoint = _redis.GetEndPoints();
            return _redis.GetServer(endpoint[i]);
        }

        private IDatabase RedisServer(int server = 1, int database = -1)
        {
            string host = AppSetting.RedisOptions.ConnectionString;
            switch (server)
            {
                case 1: host = AppSetting.RedisOptions.ConnectionString2; break;
                case 2: host = AppSetting.RedisOptions.ConnectionString3; break;
                case 3: host = AppSetting.RedisOptions.ConnectionString4; break;
                case 4: host = AppSetting.RedisOptions.ConnectionString5; break;
                case 5: host = AppSetting.RedisOptions.ConnectionString6; break;
            }
            var conn = ConnectionMultiplexer.Connect(host);
            var iDatabase = conn.GetDatabase(database);
            if (this.database == null)
            {
                this.database = iDatabase;
            }
            return iDatabase;
        }

        public string? Get(string key, int server = 0, int db = -1)
        {
            if (database == null)
            {
                RedisServer(server, db);
            }
            return database?.StringGet(key);
        }
        #region string 异步
        public async Task<bool> KeyExpireAsync(RedisKey key, TimeSpan? expiry)
        {
            return await _database.KeyExpireAsync(key, expiry);
        }
        public async Task Clear()
        {
            foreach (var endPoint in _redis.GetEndPoints())
            {
                var server = this.GetServer();
                foreach (var key in server.Keys())
                {
                    await _database.KeyDeleteAsync(key);
                }
            }
        }
        public async Task<bool> ExistAsync(string key)
        {
            return await _database.KeyExistsAsync(key);
        }

        public async Task RemoveAsync(string key)
        {
            await _database.KeyDeleteAsync(key);
        }

        public async Task<string> GetAsync(string key)
        {
            var result = await _database.StringGetAsync(key);
            return result;
        }

        public async Task<TEntity> GetAsync<TEntity>(string key)
        {
            var value = await _database.StringGetAsync(key);
            if (value.HasValue)
            {
                //需要用的反序列化，将Redis存储的Byte[]，进行反序列化
                return JsonConvert.DeserializeObject<TEntity>(value);
            }
            else
            {
                return default;
            }
        }
        public async Task SetAsync(string key, object value, TimeSpan? cacheTime = null)
        {
            if (value != null)
            {
                cacheTime = cacheTime == null ? TimeSpan.FromHours(1) : cacheTime;
                await _database.StringSetAsync(key, JsonConvert.SerializeObject(value), cacheTime);
            }
        }
        #endregion
        #region hash
        public bool HashRemove(string redisKey, string redisfiedId)
        {
            return _database.HashDelete(redisKey, redisfiedId);
        }

        public string HashGet(string redisKey, string redisfiedId)
        {
            return _database.HashGet(redisKey, redisfiedId);
        }
        public bool HashSet(string redisKey, string redisfiedId, string value)
        {
            return _database.HashSet(redisKey, redisfiedId, value);
        }

        public bool HashExist(string redisKey, string redisfiedId)
        {
            return _database.HashExists(redisKey, redisfiedId);
        }

        #endregion
        #region string 同步

        public bool KeyRename(string key, string rkey)
        {
            return _database.KeyRename(key, rkey);
        }
        public bool Exist(string key)
        {
            return _database.KeyExists(key);
        }

        public string Get(string key)
        {
            return _database.StringGet(key);
        }
        public void Remove(string key) => _database.KeyDelete(key);

        public void Set(string key, object value, TimeSpan? cacheTime = null)
        {
            cacheTime = cacheTime == null ? TimeSpan.FromHours(1) : cacheTime;
            if (value != null)
                _database.StringSet(key, JsonConvert.SerializeObject(value), cacheTime);
        }
        public TEntity Get<TEntity>(string key)
        {
            var value = _database.StringGet(key);
            if (value.HasValue)
            {
                return JsonConvert.DeserializeObject<TEntity>(value);
            }
            else
            {
                return default;
            }
        }
        #endregion

        #region List 异步
        public async Task<RedisValue[]> ListRangeAsync(string redisKey)
        {
            return await _database.ListRangeAsync(redisKey);
        }

        /// <summary>
        /// 头部插入
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue">string</param>
        /// <returns></returns>
        public async Task<long> ListLeftPushAsync(string redisKey, string redisValue)
        {
            if (redisValue == null) redisValue = "null";
            if (redisValue.Contains("null"))
            {
                redisValue = redisValue.Trim('\"');
            }
            return await _database.ListLeftPushAsync(redisKey, redisValue);
        }
        /// <summary>
        ///头部插入
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue">object</param>
        /// <returns></returns>
        public async Task<long> ListLeftPushAsync(string redisKey, object redisValue)
        {
            string value = JsonConvert.SerializeObject(redisValue);
            return await _database.ListLeftPushAsync(redisKey, value);
        }
        /// <summary>
        /// 头部插入 T实体
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public async Task ListLeftPushAsync<T>(string redisKey, List<T> redisValue)
        {
            foreach (var item in redisValue)
            {
                string value = JsonConvert.SerializeObject(item);
                await _database.ListLeftPushAsync(redisKey, value);
            }
        }

        #endregion

        /// <summary>
        /// 头部插入
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public long ListLeftPush(string redisKey, string redisValue)
        {
            if (redisValue == null) redisValue = "null";
            if (redisValue.Contains("null"))
            {
                redisValue = redisValue.Trim('\"');
            }

            return _database.ListLeftPush(redisKey, redisValue);
        }
        /// <summary>
        /// 头部插入
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public long ListLeftPush(string redisKey, object redisValue)
        {
            return _database.ListLeftPush(redisKey, JsonConvert.SerializeObject(redisValue));
        }
        /// <summary>
        /// 尾部插入
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue">string</param>
        /// <returns></returns>
        public async Task<long> ListRightPushAsync(string redisKey, string redisValue)
        {
            if (redisValue == null) redisValue = "null";
            if (redisValue.Contains("null"))
            {
                redisValue = redisValue.Trim('\"');
            }
            return await _database.ListRightPushAsync(redisKey, redisValue);
        }
        /// <summary>
        /// 尾部插入
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue">object</param>
        /// <returns></returns>
        public async Task<long> ListRightPushAsync(string redisKey, object redisValue)
        {
            string value = JsonConvert.SerializeObject(redisValue);
            return await _database.ListRightPushAsync(redisKey, value);
        }
        /// <summary>
        /// 在列表尾部
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue">数组</param>
        /// <returns></returns>
        public async Task<long> ListRightPushAsync(string redisKey, IEnumerable<string> redisValue)
        {
            var redislist = new List<RedisValue>();
            foreach (var item in redisValue)
            {
                redislist.Add(item);
            }
            return await _database.ListRightPushAsync(redisKey, redislist.ToArray());
        }

        public async Task<long> ListRightPushAsync<T>(string redisKey, IEnumerable<T> redisValue)
        {
            var redislist = new List<RedisValue>();
            foreach (var item in redisValue)
            {
                redislist.Add(JsonConvert.SerializeObject(item));
            }
            return await _database.ListRightPushAsync(redisKey, redislist.ToArray());
        }

        public long ListInsertAfter(string redisKey, string redisValue, string redisValue1)
        {
            return _database.ListInsertAfter(redisKey, redisValue, redisValue1);
        }

        /// <summary>
        /// 在列表头部插入值。如果键不存在，先创建再插入值
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public void ListLeftPush<T>(string redisKey, List<T> redisValue)
        {
            var redisValues = redisValue.Select(x => new RedisValue(JsonConvert.SerializeObject(x))).ToArray();
            if (redisValues != null && redisValues.Count() > 0)
            {
                _database.ListLeftPush(redisKey, redisValues);
            }
        }
        /// <summary>
        /// 修改LIST指定位置值
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public async Task ListSetAtAsync(string redisKey, long at, object redisValue)
        {
            string value = JsonConvert.SerializeObject(redisValue);
            var idx = await _database.ListGetByIndexAsync(redisKey, at);
            await _database.ListInsertBeforeAsync(redisKey, idx, value);
            return;
        }
        /// <summary>
        /// 获取LIST指定位置值 并删除
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public async Task<T> ListGetAtAsync<T>(string redisKey, long at) where T : class
        {
            var value = await _database.ListGetByIndexAsync(redisKey, at);
            if (string.IsNullOrEmpty(value)) return null;
            await _database.ListRemoveAsync(redisKey, value);
            var result = JsonConvert.DeserializeObject<T>(value);
            return result;
        }

        /// <summary>
        /// 在列表头部插入值。如果键不存在，先创建再插入值
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public async Task ListRightPushAsync<T>(string redisKey, List<T> redisValue)
        {
            foreach (var item in redisValue)
            {
                string value = JsonConvert.SerializeObject(item);
                await _database.ListRightPushAsync(redisKey, value);
            }
        }

        /// <summary>
        /// 在列表头部插入值。如果键不存在，先创建再插入值
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public void ListRightPush<T>(string redisKey, List<T> redisValue)
        {
            foreach (var item in redisValue)
            {
                string value = JsonConvert.SerializeObject(item);
                _database.ListRightPush(redisKey, value);
            }
        }

        /// <summary>
        /// 在列表头部插入值。如果键不存在，先创建再插入值
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public long ListRightPush(string redisKey, string redisValue)
        {
            if (redisValue == null) redisValue = "null";
            if (redisValue.Contains("null"))
            {
                redisValue = redisValue.Trim('\"');
            }
            return _database.ListRightPush(redisKey, redisValue);
        }
        /// <summary>
        /// 在列表头部插入值。如果键不存在，先创建再插入值
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public long ListRightPush(string redisKey, object redisValue)
        {
            return _database.ListRightPush(redisKey, JsonConvert.SerializeObject(redisValue));
        }




        /// <summary>
        /// 修改LIST指定位置值
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public void ListSetAt(string redisKey, long at, object redisValue)
        {
            string value = JsonConvert.SerializeObject(redisValue);
            _database.ListSetByIndex(redisKey, at, value);
            return;
        }


        /// <summary>
        /// 获取LIST指定位置值 并删除
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public T ListGetAt<T>(string redisKey, long at) where T : class
        {
            var value = _database.ListGetByIndex(redisKey, at);
            if (string.IsNullOrEmpty(value)) return null;
            _database.ListRemove(redisKey, value);
            var result = JsonConvert.DeserializeObject<T>(value);
            return result;
        }
        /// <summary>
        /// 获取LIST指定位置值 并删除
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public string ListGetAt(string redisKey, long at)
        {
            var value = _database.ListGetByIndex(redisKey, at);

            if (!string.IsNullOrEmpty(value))
            {
                _database.ListRemove(redisKey, value);
            }
            return value;
        }

        /// <summary>
        /// 获取LIST指定位置值 
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public T GetListIndex<T>(string redisKey, long at) where T : class
        {
            var value = _database.ListGetByIndex(redisKey, at);
            if (string.IsNullOrEmpty(value))
            {
                return null;
            }
            var result = JsonConvert.DeserializeObject<T>(value);
            return result;
        }
        /// <summary>
        /// 获取LIST指定位置值 
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="redisValue"></param>
        /// <returns></returns>
        public string GetListIndex(string redisKey, long at)
        {
            var value = _database.ListGetByIndex(redisKey, at);

            return value;
        }



        /// <summary>
        /// 移除并返回存储在该键列表的第一个元素  反序列化
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public async Task<T> ListLeftPopAsync<T>(string redisKey) where T : class
        {
            var cacheValue = await _database.ListLeftPopAsync(redisKey);
            if (string.IsNullOrEmpty(cacheValue)) return null;
            var res = JsonConvert.DeserializeObject<T>(cacheValue);
            return res;
        }

        /// <summary>
        /// 移除并返回存储在该键列表的第一个元素  反序列化
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public T ListLeftPop<T>(string redisKey) where T : class
        {
            var cacheValue = _database.ListLeftPop(redisKey);
            if (string.IsNullOrEmpty(cacheValue)) return null;
            var res = JsonConvert.DeserializeObject<T>(cacheValue);
            return res;
        }


        /// <summary>
        /// 移除并返回存储在该键列表的最后一个元素   反序列化
        /// 只能是对象集合
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public async Task<T> ListRightPopAsync<T>(string redisKey) where T : class
        {
            var cacheValue = await _database.ListRightPopAsync(redisKey);
            if (string.IsNullOrEmpty(cacheValue)) return null;
            var res = JsonConvert.DeserializeObject<T>(cacheValue);
            return res;
        }
        /// <summary>
        /// 移除并返回存储在该键列表的最后一个元素   反序列化
        /// 只能是对象集合
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public T ListRightPop<T>(string redisKey) where T : class
        {
            var cacheValue = _database.ListRightPop(redisKey);
            if (string.IsNullOrEmpty(cacheValue)) return null;
            var res = JsonConvert.DeserializeObject<T>(cacheValue);
            return res;
        }

        /// <summary>
        /// 移除并返回存储在该键列表的第一个元素   
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public async Task<string> ListLeftPopAsync(string redisKey)
        {
            return await _database.ListLeftPopAsync(redisKey);
        }

        /// <summary>
        /// 移除并返回存储在该键列表的第一个元素   
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public string ListLeftPop(string redisKey)
        {
            return _database.ListLeftPop(redisKey);
        }
        /// <summary>
        /// 移除并返回存储在该键列表的最后一个元素   
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public async Task<string> ListRightPopAsync(string redisKey)
        {
            return await _database.ListRightPopAsync(redisKey);
        }
        /// <summary>
        /// 移除并返回存储在该键列表的最后一个元素   
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public string ListRightPop(string redisKey)
        {
            return _database.ListRightPop(redisKey);
        }

        /// <summary>
        ///  
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public string ListRight(string redisKey)
        {
            return _database.ListRightPop(redisKey);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourceKey"></param>
        /// <param name="destination"></param>
        /// <returns></returns>
        public string ListRightPopLeftPush(string sourceKey, string destination)
        {
            return _database.ListRightPopLeftPush(sourceKey, destination);
        }

        /// <summary>
        /// 列表长度
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public async Task<long> ListLengthAsync(string redisKey)
        {
            return await _database.ListLengthAsync(redisKey);
        }
        /// <summary>
        /// 列表长度
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public long ListLength(string redisKey)
        {
            return _database.ListLength(redisKey);
        }
        /// <summary>
        /// 返回在该列表上键所对应的元素
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public async Task<IEnumerable<string>> ListRangeAsync(string redisKey, int db = -1)
        {
            var result = await _database.ListRangeAsync(redisKey);
            return result.Select(o => o.ToString());
        }
        /// <summary>
        /// 返回在该列表上键所对应的元素
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="start"></param>
        /// <param name="stop"></param>
        /// <returns></returns>
        public async Task<IEnumerable<string>> ListRangeAsync(string redisKey, int start, int stop)
        {
            var result = await _database.ListRangeAsync(redisKey, start, stop);
            return result.Select(o => o.ToString());
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="start"></param>
        /// <param name="stop"></param>
        /// <returns></returns>
        public IEnumerable<string> ListRange(string redisKey, int start, int stop)
        {
            var result = _database.ListRange(redisKey, start, stop);
            return result.Select(o => o.ToString());
        }
        /// <summary>
        /// 获取list 第一个数据
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="start"></param>
        /// <param name="stop"></param>
        /// <returns></returns>
        public string ListRangeFirst(string redisKey)
        {
            var result = _database.ListRange(redisKey, 0).FirstOrDefault();
            return result;
        }

        /// <summary>
        /// 获取最后数据
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="start"></param>
        /// <param name="stop"></param>
        /// <returns></returns>
        public T ListRangeLast<T>(string redisKey)
            where T : class, new()
        {
            var result = _database.ListRange(redisKey, -1);
            if (result == null || result.Length == 0) return null;
            var value = result.FirstOrDefault();
            return JsonConvert.DeserializeObject<T>(value);
        }
        /// <summary>
        /// 获取最后数据
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="start"></param>
        /// <param name="stop"></param>
        /// <returns></returns>
        public string ListRangeLast(string redisKey)
        {
            var result = _database.ListRange(redisKey, -1).FirstOrDefault();
            return result;
        }

        /// <summary>
        ///  返回在该列表上键所对应的元素 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<T>> ListRangeAsync<T>(string redisKey) where T : class
        {
            var result = await _database.ListRangeAsync(redisKey);
            if (result == null || result.Length <= 0) return null;
            var resultstr = result.Select(o => o.ToString());
            List<T> values = new List<T>();
            foreach (var item in resultstr)
            {
                values.Add(JsonConvert.DeserializeObject<T>(item));
            }
            return values;
        }
        /// <summary>
        ///  返回在该列表上键所对应的元素 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public List<T> ListRange<T>(string redisKey) where T : class
        {
            var result = _database.ListRange(redisKey);
            if (result == null || result.Length <= 0) return null;
            var resultstr = result.Select(o => o.ToString());
            List<T> values = new List<T>();
            foreach (var item in resultstr)
            {
                if (item == null || item == "null")
                {
                    values.Add(null);
                }
                else
                {
                    values.Add(JsonConvert.DeserializeObject<T>(item));
                }
            }
            return values;
        }
        /// <summary>
        /// 获取LIST所有值
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public List<string> ListRange(string redisKey)
        {
            var values = _database.ListRange(redisKey);
            return values.Select(m=>m.ToString()).ToList();
        }
        /// <summary>
        /// 删除List中的元素 并返回删除的个数
        /// </summary>
        /// <param name="redisKey">key</param>
        /// <param name="redisValue">元素</param>
        /// <param name="type">大于零 : 从表头开始向表尾搜索，小于零 : 从表尾开始向表头搜索，等于零：移除表中所有与 VALUE 相等的值</param>
        /// <returns></returns>
        public async Task<long> ListDelRangeAsync(string redisKey, string redisValue, long type = 0)
        {
            return await _database.ListRemoveAsync(redisKey, redisValue, type);
        }

        /// <summary>
        /// 删除List中的元素 并返回删除的个数
        /// </summary>
        /// <param name="redisKey">key</param>
        /// <param name="redisValue">元素</param>
        /// <param name="type">大于零 : 从表头开始向表尾搜索，小于零 : 从表尾开始向表头搜索，等于零：移除表中所有与 VALUE 相等的值</param>
        /// <returns></returns>
        public long ListDelRange(string redisKey, string redisValue, long type = 0)
        {
            return _database.ListRemove(redisKey, redisValue, type);
        }
        /// <summary>
        /// 清空List
        /// </summary>
        /// <param name="redisKey"></param>
        public async Task ListClearAsync(string redisKey)
        {
            await _database.ListTrimAsync(redisKey, 1, 0);
        }
        /// <summary>
        /// 清空List
        /// </summary>
        /// <param name="redisKey"></param>
        public void ListClear(string redisKey)
        {
            _database.ListTrim(redisKey, 1, 0);
        }
        #region  有序集合 zset
        /// <summary>
        /// 有序集合/定时任务延迟队列用的多
        /// </summary>
        /// <param name="redisKey">key</param>
        /// <param name="redisValue">元素</param>
        /// <param name="score">分数</param>
        public async Task SortedSetAddAsync(string redisKey, string redisValue, double score)
        {
            await _database.SortedSetAddAsync(redisKey, redisValue, score);

        } /// <summary>
          /// 有序集合的长度
          /// </summary>
          /// <param name="redisKey"></param>
          /// <returns></returns>
        public long SortedLength(string redisKey)
        {
            return _database.SortedSetLength(redisKey);
        }
        /// <summary>
        /// 有序集合/定时任务延迟队列用的多
        /// </summary>
        /// <param name="redisKey">key</param>
        /// <param name="redisValue">元素</param>
        /// <param name="score">分数</param>
        public void SortedSetAdd(string redisKey, string redisValue, double score)
        {
            _database.SortedSetAdd(redisKey, redisValue, score);

        }
        #endregion
        /// <summary>
        /// 自增
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<long> IncrAsync(string key, int value = 1)
        {
            return await _database.StringIncrementAsync(key, value);
        }
        /// <summary>
        /// 自增
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public long Incr(string key, int value = 1)
        {
            return _database.StringIncrement(key, value);
        }
        /// <summary>
        /// 获取key剩余过期时间
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>

        public async Task<TimeSpan?> KeyTimeAsync(string key)
        {
            return await _database.KeyTimeToLiveAsync(key);
        }

        /// <summary>
        ///  获取key剩余过期时间
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public TimeSpan? KeyTime(string key)
        {
            return _database.KeyTimeToLive(key);
        }




        /// <summary>
        /// 设置key 过期时间
        /// </summary>
        /// <param name="key"></param>
        /// <param name="expiry"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool KeyExpire(RedisKey key, TimeSpan? expiry)
        {
            return _database.KeyExpire(key, expiry);
        }
        /// <summary>
        /// 获取LIST指定值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public string? ListGetByIndex(string key, long index)
        {
            string? value = _database.ListGetByIndex(key, index);
            return value;
        }

        /// <summary>
        /// 获取LIST指定对象
        /// </summary>
        /// <param name="key"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public T? ListGetByIndex<T>(string key, long index)
        {
            string? value = _database.ListGetByIndex(key, index);
            T? result = JsonConvert.DeserializeObject<T>(value);
            return result;
        }

        /// <summary>
        /// 在LIST指定对象前添加
        /// </summary>
        /// <param name="key"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public void ListInsertBeforeIndex(string key, object data, long index)
        {
            string before = _database.ListGetByIndex(key, index);
            string value = JsonConvert.SerializeObject(data);
            _database.ListInsertBefore(key, before, value);
        }

        /// <summary>
        /// 在LIST指定对象后添加
        /// </summary>
        /// <param name="key"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public void ListInsertAfterIndex(string key, object data, long index)
        {
            string before = _database.ListGetByIndex(key, index);
            string value = JsonConvert.SerializeObject(data);
            _database.ListInsertAfter(key, before, value);
        }

        #region 弃用
        /// <summary>
        /// 批量设置KEY值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="cacheTime"></param>
        /// <returns></returns>
        public async Task BatchSetAsync<T>(string key, List<T> value, TimeSpan? cacheTime = null)
        {
            try
            {
                var db = _redis.GetDatabase();
                //批量过来的数据：
                var setData = value;
                var batch = db.CreateBatch();
                int i = 1;
                cacheTime = cacheTime == null ? TimeSpan.FromHours(1) : cacheTime;
                foreach (var item in value)
                {
                    var keyvalue = $"{key}{i}";
                    var result = JsonConvert.SerializeObject(item);

                    batch.StringSetAsync(keyvalue, result, cacheTime).ConfigureAwait(false);
                    batch.KeyExpireAsync(keyvalue, cacheTime).ConfigureAwait(false); ;
                    i++;
                }
                batch.Execute();
            }
            catch (Exception ex)
            {

                throw;
            }

        }
        /// <summary>
        /// 模糊删除
        /// </summary>
        /// <param name="key"></param>
        public async Task LikeRemoveAsync(string pattern)
        {
            var redisResult = _redis.GetDatabase().ScriptEvaluate(LuaScript.Prepare(
                            //Redis的keys模糊查询：
                            " local res = redis.call('KEYS', @keypattern) " +
                            " return res "), new { @keypattern = pattern });

            if (!redisResult.IsNull)
            {
                RedisKey[] preSult = (RedisKey[])redisResult;
                _redis.GetDatabase().KeyDeleteAsync(preSult);
            }
        }
        /// <summary>
        /// 模糊查询 wafer 专用
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<List<TEntity?>> GetLikeEntityAsync<TEntity>(string key)
        {
            List<TEntity?> result = new List<TEntity?>();
            try
            {
                List<RedisKey> redisKeys = new List<RedisKey>();
                for (int i = 1; i <= 120; i++)
                {
                    var sresult = new RedisKey($"{key}{i}");
                    redisKeys.Add(sresult);
                }
                var Tags = await _redis.GetDatabase().StringGetAsync(redisKeys.ToArray());
                if (Tags != null)
                {
                    result = Tags.Where(a => !a.IsNull).Select(o => JsonConvert.DeserializeObject<TEntity>(o.ToString())).ToList();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
            finally
            {
                if (result == null)
                {
                    result = new List<TEntity>();
                }
            }
            return result;
        }
        #endregion

        #region Redis Keys
        public List<string> GetKeys(string name)
        {
            List<string> listKeys = new List<string>();
            foreach (var endPoint in _redis.GetEndPoints())
            {
                var server = _redis.GetServer(endPoint);
                var list = server.Keys(0, name).Select(m => m.ToString()).ToList();
                listKeys.AddRange(list);
            }
            return listKeys;
        }
        #endregion

    }
}



